package com.gonsin.gnews.utils;

import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

public class FreemarkerUtils {


//    /**
//     * 用freemarker框架注入字符串
//     */
//    public static String generalString(String in, Map<String, Object> params){
//        if(params == null || params.isEmpty()){
//            return in;
//        }
//        Configuration conf = new Configuration(Configuration.VERSION_2_3_22);
//        conf.setObjectWrapper(new BeansWrapperBuilder(Configuration.VERSION_2_3_22).build());
//        Template t = null;
//        try {
//            t = new Template("templateName", new StringReader(in), conf);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        Writer out = new StringWriter();
//        try {
//            t.process(params, out);
//        } catch (TemplateException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String content = out.toString();
//        return content;
//    }


    /**
     * 用freemarker框架注入字符串
     */
    public static String generalString(String in, Object params){
        if(params == null){
            return in;
        }
        Configuration conf = new Configuration(Configuration.VERSION_2_3_22);
        conf.setObjectWrapper(new BeansWrapperBuilder(Configuration.VERSION_2_3_22).build());
        Template t = null;
        try {
            t = new Template("templateName", new StringReader(in), conf);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Writer out = new StringWriter();
        try {
            t.process(params, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String content = out.toString();
        return content;
    }
}
